<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/9
 * Time: 16:27
 */

namespace app\admin\controller;


use app\admin\logic\MessageLogic;
use app\admin\logic\OwnerLogic;
use app\common\controller\Backend;
use app\common\utils\Constant;
use app\common\utils\IDCardUtils;
use app\common\utils\PHPExcelUtils;
use think\Db;
use think\Exception;


/**
 * 业主管理
 * Class Owner
 * @package app\admin\controller
 */
class Owner extends Backend
{
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Owner');
    }

    /**
     * 查看
     */
    public function index()
    {

        if ($this->request->isAjax())
        {
            $userId = $this->auth->id;
            $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
            $map = [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($user['user_type'] == Constant::USER_TYPE_PROPERTY) {
                $villageIds = $this->getVillageIds($user['property_id']);
                $map['house_property.village_id'] = array('in', $villageIds);
            }
            $prefix = config('database.prefix');
            $total = $this->model
                ->join('house_property',$prefix.'owner.id=house_property.owner_id', 'LEFT')
                ->where($where)
                ->where($map)
//                ->order($sort, $order)
                ->group($prefix.'owner.id')
                ->count();
            $list = $this->model
                ->join('house_property',$prefix.'owner.id=house_property.owner_id', 'LEFT')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->field($prefix.'owner.*')
                ->group($prefix.'owner.id')
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                Db::startTrans();
                try {
                    if(!is_mobile($params['phone'])){
                        $this->error('手机号格式不正确！');
                    }
                    if(!IDCardUtils::getInstance()->validation_filter_id_card($params['id_card'])){
                        $this->error('身份证号格式不正确！');
                    }
                    $phone_count = $this->model
                        ->where('phone', 'eq', $params['phone'])
                        ->count();
                    if ($phone_count > 0) {
                        $this->error('该手机号已经被绑定过！');
                    }
                    $id_card_count = $this->model
                        ->whereOr('id_card', 'eq', $params['id_card'])
                        ->count();
                    if($id_card_count > 0){
                        $this->error('该身份证号已经被绑定过！');
                    }
                    $house_property = $params['house'];
                    unset($params['house']);
                    $obj = $this->model->create($params);
                    $house_property['owner_id'] = $obj['id'];
                    $house_property['charge_total'] = $house_property['water_charge'] + $house_property['property_charge'];
                    model('HouseProperty')->insert($house_property);
                    Db::commit();
                    $this->success('添加成功！');
                }catch (Exception $e){
                    Db::rollback();
                    $this->error('添加失败！','',$e->getMessage());
                }
            }
            $this->error('添加失败！');
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {


            $params = $this->request->post("row/a");
            if ($params)
            {
                Db::startTrans();
                try {
                    if(!is_mobile($params['phone'])){
                        $this->error('手机号格式不正确！');
                    }
                    if(!IDCardUtils::getInstance()->validation_filter_id_card($params['id_card'])){
                        $this->error('身份证号格式不正确！');
                    }
                    $count = model('HouseProperty')->where(array('owner_id'=>$ids))->count();
                    if($count > 1){
                        $this->error('该用户绑定多个房产，无法修改信息！');
                    }
                    $phone_count = $this->model
                        ->where('phone', 'eq', $params['phone'])
                        ->where('id', 'neq', $ids)
                        ->count();
                    if ($phone_count > 0) {
                        $this->error('该手机号已经被绑定过！');
                    }
                    $id_card_count = $this->model
                        ->whereOr('id_card', 'eq', $params['id_card'])
                        ->where('id', 'neq', $ids)
                        ->count();
                    if($id_card_count > 0){
                        $this->error('该身份证号已经被绑定过！');
                    }
                    $row->save($params);
                    Db::commit();
                    $this->success('修改成功！');
                }catch (Exception $e){
                    Db::rollback();
                    $this->error('修改失败！','',$e->getMessage());
                }
            }

            $this->error('修改失败！');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            Db::startTrans();
            try {
                //删除房产信息
                model('HouseProperty')->where(array('owner_id'=>$ids))->delete();
                $result = $this->model->destroy($ids);
                if($result){
                    Db::commit();
                    $this->success('删除成功!');
                }else {
                    $this->error('删除失败!');
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error('删除失败!');
            }

        }
        $this->error();
    }

    /**
     * 导入
     */
    public function import(){
        if ($this->request->isAjax())
        {
            ignore_user_abort();
            set_time_limit(0);
            $village_id = $this->request->post('village_id');
            $file_path = $this->request->post('file_path');
            $logic = new OwnerLogic();
            $admin_id = $this->auth->id;
            $result = $logic->import($file_path,$village_id,$admin_id);
            $msg = '';
            $success = false;
            $rtnData = array();
            switch($result['status']){
                case 0:
                    $msg = $result['msg'];
                    break;
                case 1:
                    $success = true;
                    unlink($file_path);//删除文件
                    break;
                case 2:
                    $msg = $result['msg'];
                    break;
            }
            if($success){
                $this->success('导入成功！');
            }else{
                $this->error($msg,'',$rtnData);
            }
        }
        return $this->view->fetch();
    }

    /**
     * 业主导入模板
     */
    public function download_template(){
        $phpExcelUtil = new PHPExcelUtils();
        $cellList = array('业主名', '身份证号', '手机号', '大楼编号', '楼层号','房间号','详细地址','未缴水费','未缴物业费');
        $obj = $phpExcelUtil->setCellList($cellList);
        $fileName = iconv("utf-8", "gb2312", '业主房产导入模板.xls');
        $obj->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

}